import { Form, Input, Modal, message } from 'antd';
import { useRef } from 'react';
import { addUser } from '../../../services/user';

interface AddFormProps {
  onClose: () => void;
}

const AddForm = (props: AddFormProps) => {
  const [form] = Form.useForm();
  const saving = useRef(false);

  const handlerAdd = () => {
    if (saving.current) {
      return;
    }
    saving.current = true;
    form.validateFields().then((values) => {

      addUser(values).then((res: any) => {
        saving.current = false;
        if (res.data.code === 200) {
          props.onClose();
        } else {
          message.warning(res.data.message);  
        }
      }, (err: any) => {
        saving.current = false;
        message.warning(err);
      });
    }, () => {
      saving.current = false;
    });
  };

  return (
    <Modal open={true} onCancel={props.onClose} width={700} onOk={handlerAdd}>
      <Form
        style={{ padding: 24 }}
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: '请输入姓名' }]}
        >
          <Input placeholder='请输入姓名' />
        </Form.Item>
        <Form.Item
          label="昵称"
          name="nickname"
          rules={[{ required: true, message: '请输入昵称' }]}
        >
          <Input placeholder='请输入昵称' />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input type="password" placeholder='请输入密码' />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddForm;
